package com.example.video.util.laixiOperate;

import com.example.video.common.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.List;

@Component
@Slf4j
public class Operate {
    @Resource
    private LAIXICmd laixiCmd;

    @Value("${ServerUrl}")
    private String serverUrl;

    public static void main(String[] args) {
//        log.info("operate -> msg: "+createDevice());
//        log.info(excuJs( List.of("b8055af"),"request"));

    }


    /**
     * 获取缓存分组
     * @return
     */
    public String getCacheGroup() throws URISyntaxException, InterruptedException {
        return laixiCmd.cmdGetCacheGroup();
    }


    /**
     * 在删除账户时，删除其下对应的设备
     * @param groupId 用户的分组id
     * @param deviceIds 设备id
     * @return 返回结果
     */
    public Result<String> deleteDevice(String groupId, List<String> deviceIds) throws URISyntaxException, InterruptedException {
        Result<String> rs = new Result<>();
        JSONObject jsonObject = new JSONObject(laixiCmd.cmdMvDeviceToGroup(groupId, "0", deviceIds));
        if(!jsonObject.isNull("StatusCode")){
            if(jsonObject.getInt("StatusCode") == 200){
                rs.setCode(0);
                rs.setMsg("移动成功！");
            }
        }else{
            rs.setCode(-1);
            rs.setMsg("移动失败！");
        }

        return rs;
    }


    /**
     * 在接收到设备上传账户设置成功后，执行此函数，将设备移动到该用户下的分组
     * @param groupId 用户的分组id
     * @param deviceIds 设备id
     * @return 返回结果
     */
    public Result<String> moveDeviceToGroup(String groupId, List<String> deviceIds) throws URISyntaxException, InterruptedException {

        Result<String> rs = new Result<>();
        JSONObject jsonObject = new JSONObject(laixiCmd.cmdMvDeviceToGroup(laixiCmd.cmdGetCacheGroup(), groupId, deviceIds));
        if(!jsonObject.isNull("StatusCode")){
            if(jsonObject.getInt("StatusCode") == 200){
                rs.setCode(0);
                rs.setMsg("移动成功！");
            }
        }else{
            rs.setCode(-1);
            rs.setMsg("移动失败！");
        }

        return rs;
    }


    /**
     * 指定设备执行对应脚本
     * @param deviceIds
     * @param name
     * @return
     */
    public Result<String> excuJs(List<String> deviceIds, String name) throws URISyntaxException, InterruptedException {
        Result<String> rs = new Result<>();
        rs.setCode(-1);
        rs.setMsg("执行失败！");
        rs.setCount(0);
        rs.setData(null);
        String result = laixiCmd.cmdExcuJs(deviceIds,name);
        log.info("Operate -> excuJs ->msg: "+result);
        JSONObject object = new JSONObject(result);
        if(!object.isNull("StatusCode")){
            if(object.getInt("StatusCode") == 200){
                rs.setCode(0);
                rs.setMsg("执行成功！");
            }
        }

        return rs;
    }


    /**
     * 创建新角色时，创建新分组
     * @param role
     * @return
     */
    public Result<String> createGroup(String role) throws URISyntaxException, InterruptedException {
        Result<String> rs = new Result<>();
        rs.setCode(-1);
        rs.setMsg("执行失败！");
        rs.setCount(0);
        rs.setData(null);
        JSONObject object = new JSONObject( laixiCmd.cmdCreateGroup(role) );

        // StatusCode是来喜服务端返回的数据，表示执行状态，
        // result表示返回的分组id
        if(!object.isNull("StatusCode")){
            if(object.getInt("StatusCode") == 200){
                if(!object.isNull("result")){
                    rs.setData(object.getString("result"));
                }
                rs.setCode(0);
                rs.setMsg("执行成功！");
            }
        }
        return rs;
    }

    /**
     * 新建源账户后，给该账户分配一个设备
     * @return 返回绑定的设备id
     */
    public Result<String> createDevice() throws URISyntaxException, InterruptedException {
        Result<String> rs = new Result<>();
        rs.setCode(-1);
        rs.setMsg("执行失败！");
        rs.setCount(0);
        rs.setData(null);

        JSONObject object = new JSONObject( laixiCmd.cmdGetDeviceIds() );
        // StatusCode是来喜服务端返回的数据，表示执行状态，
        // result表示返回的设备id
        // 查询所有设备，查找未分组设备
        if(!object.isNull("StatusCode")){
            if(object.getInt("StatusCode") == 200){
                log.info("Operate -> createDevice ->msg: 查找所有设备："+object.getString("result"));
                if(!object.isNull("result")){
                    JSONArray array = new JSONArray(object.getString("result"));

                    int flag = 0;
                    for(int i = 0; i < array.length(); i++){
                        JSONObject jsonObject = array.getJSONObject(i);

                        // 如果是未分组的设备，则分配到该分组
                        if(jsonObject.getInt("groupId") == 0){
                            flag = 1;
                            String mvResult = laixiCmd.cmdMvDeviceToGroup("0", laixiCmd.cmdGetCacheGroup(), List.of(jsonObject.getString("deviceId")));
                            JSONObject mvObject = new JSONObject(mvResult);
                            log.info("Operate -> createDevice ->msg: 修改分组："+mvResult);
                            if(!mvObject.isNull("StatusCode")){
                                if(mvObject.getInt("StatusCode") == 200){
                                    if(!mvObject.isNull("result")){
                                        log.info("Operate -> createDevice ->msg: 进入操作");
                                        String deviceId = jsonObject.getString("deviceId");
                                        // 先让向设备的剪切板中设置设备id
                                        // 失效
//                                        laixiCmd.cmdSetIdToClip(List.of(groupId));
                                        // 发送创建文件脚本--7.18
//                                        log.info("Operate -> createDevice ->msg: 创建设备id文件："+laixiCmd.cmdExcuJs(List.of(deviceId), "createDir"));

                                        // 使用adb命令，写入一个文件，该文件名为 deviceId---7.18修改：不创建文件，而是把id写入id文件中
                                        // 8.21修改：adb命令创建的文件不能被autojs脚本扫描到，改用让手机下载id文件
//                                        log.info("Operate -> createDevice ->msg: 写入id到id文件："+laixiCmd.cmdAdbWriteIdFile(deviceId));
                                        // 让手机下载id文件
                                        String url = serverUrl.replace("resource/","device/getDeviceId?id=" +deviceId);
                                        log.info("Operate -> createDevice ->msg: 发起下载id请求 "+laixiCmd.cmdSendHttp(deviceId, url, deviceId+".id"));
                                        // 执行初始化脚本
                                        log.info("Operate -> createDevice ->msg: 执行初始化脚本："+laixiCmd.cmdExcuJs(List.of(deviceId), "init"));
                                        log.info("Operate -> createDevice ->msg: 执行完成绑定脚本："+laixiCmd.cmdExcuJs(List.of(deviceId), "bind"));

                                        rs.setData(deviceId);
                                        rs.setCode(0);
                                        rs.setMsg("执行成功！");
                                    }else{
                                        log.info("Operate -> createDevice ->msg: 进入操作失败！");
                                    }

                                }
                            }
                            break;
                        }
                    }
                    if(flag == 1 && rs.getCode() == -1){
                        rs.setMsg("转移分组失败！");
                    }else if(flag == 0){
                        rs.setMsg("无可用设备！请联系管理员！");
                    }
                }

            }
        }
        return rs;
    }



    /**
     * 查询该分组下的设备
     * @param groupId 分组id
     */
//    public static Result<String> getGroupDevices(String groupId){
//
//    }

    /**
     * 查看所有设备
     */
    public   Result<String> getGroup(String test) throws URISyntaxException, InterruptedException {
        log.info("Operate -> getGroup ->msg: "+test);
        Result<String> rs = new Result<>();
        rs.setMsg("成功！");
        rs.setData(laixiCmd.cmdGetGroup());
        return rs;
    }

    public String deviceInit(String deviceId) throws URISyntaxException, InterruptedException {
        String url = serverUrl.replace("resource/","device/getDeviceId?id=" +deviceId);
        log.info("Operate -> createDevice ->msg: 发起下载id请求 "+laixiCmd.cmdSendHttp(deviceId, url, deviceId+".id"));
        // 执行初始化脚本
        String result = laixiCmd.cmdExcuJs(List.of(deviceId), "init");

        log.info("Operate -> createDevice ->msg: 执行绑定脚本："+ laixiCmd.cmdExcuJs(List.of(deviceId), "bind"));

        log.info("Operate -> createDevice ->msg: 执行初始化脚本："+result);

        return result;
    }
}
